package com.file.system.controller.business;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.file.system.entity.business.*;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.system.WebFile;
import com.file.system.plugin.file.FileTool;
import com.file.system.service.business.IBusUtensilIndentService;
import com.file.system.service.business.IBusUtensilService;
import com.file.system.service.system.IWebFileService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import java.io.File;
import java.io.IOException;
import java.nio.file.StandardCopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;


/**
 * 订单、器具文件
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/bus/file")
public class BusFileController {

    private static final Logger logger = LogManager.getLogger(BusFileController.class);

    @Autowired
    private FileTool fileTool;
    @Autowired
    private IBusUtensilIndentService iBusUtensilIndentService;
    @Autowired
    private IBusUtensilService iBusUtensilService;

//    private static final String uploadPath = "G:/sign/upload/";
    private static final String uploadPath = "/sofe/web/sign/upload";
//    private static final String uploadPath = "/users/baokun/sign/upload/";


    /**
     * 下载订单
     *
     * @param ids 订单ids
     * @apiNote -
     * @author jch
     */
    @PostMapping("/download/indent")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String ids = request.getParameter("ids");
        String filePath = uploadPath + IdUtil.randomUUID() + ".xlsx";

        try (ExcelWriter excelWriter = EasyExcel.write(filePath).build()) {
            // 查询订单数据
            List<BusUtensilIndentExcel> utensilIndentExcelList = iBusUtensilIndentService.selectIndentExcelList(ids);
            // 查询器具信息
            List<BusUtensilExcel> utensilExcelList = iBusUtensilService.selectUtensilExcelListByIds(ids);

            for (int i = 0; i < utensilIndentExcelList.size(); i++) {
                int index = i + 1;
                BusUtensilIndentExcel indentExcel = utensilIndentExcelList.get(i);
                indentExcel.setIndex(String.valueOf(index));
                utensilExcelList.stream()
                        .filter(l -> l.getFkIndentId() == indentExcel.getId())
                        .forEach(l -> l.setIndex(String.valueOf(index)));
            }

            // 写入订单数据
            WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "Sheet1").head(BusUtensilIndentExcel.class).build();
            excelWriter.write(utensilIndentExcelList, writeSheet0);

            // 写入器具信息
            WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "Sheet2").head(BusUtensilExcel.class).build();
            excelWriter.write(utensilExcelList, writeSheet1);
        }

        fileTool.download(filePath, response, "委托单信息-" + DateUtil.now() + ".xlsx");
    }


    /**
     * 下载器具
     *
     * @param fkIndentId 订单id
     * @apiNote -
     * @author jch
     */
    @GetMapping("/download/utensil/{fkIndentId}")
    public void download(HttpServletResponse response,
                         @PathVariable
                         @Min(value = 1, message = "订单id长度最小1")
                         Long fkIndentId) {
        String filePath = uploadPath + IdUtil.randomUUID() + ".xlsx";
        EasyExcel.write(filePath, BusUtensilExcel.class)
                .sheet("器具信息")
                .doWrite(() -> {
                    // 分页查询数据
                    return iBusUtensilService.selectUtensilExcelList(fkIndentId);
                });
        fileTool.download(filePath, response, "器具信息-" + DateUtil.now() + ".xlsx");
    }

    /**
     * 上传订单
     *
     * @param file 文件流
     * @return CommonResult<WebFile>
     * @apiNote -
     * @author jch
     */
    @PostMapping("/indent/upload")
    public CommonResult indentUpload(@RequestParam("file") MultipartFile file) {
        // 判断上传目录是否存在，不存在则创建
        createUploadDirectory(uploadPath);

        // 判断文件后缀是否为xls或xlsx
        if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
            return CommonResult.fail().setText("文件格式错误！");
        }

        String filePath = uploadPath + file.getOriginalFilename();
        // 进行文件上传操作
        try {
            if (file.isEmpty()) {
                return CommonResult.fail().setText("上传文件为空！");
            }
            Files.copy(file.getInputStream(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail().setText("文件上传失败！");
        }

        try {
            EasyExcel.read(filePath, BusUtensilIndentExcel.class, new BusUtensilIndentListener()).sheet().doRead();
        } catch (Exception e) {
            String newFilePath = filePath.replace(".xls", ".xlsx");
            renameAndSaveFile(filePath, newFilePath);
            filePath = newFilePath;
            try {
                // 重新执行文件读取
                EasyExcel.read(filePath, BusUtensilIndentExcel.class, new BusUtensilIndentListener()).sheet().doRead();
            } catch (Exception ex) {
                return CommonResult.fail().setText("文件读取失败！");
            }
        }
        return CommonResult.ok();
    }


    /**
     * 上传器具
     *
     * @param file       文件流
     * @param fkIndentId 订单id
     * @return CommonResult<WebFile>
     * @apiNote -
     * @author jch
     */
    @PostMapping("/busUtensil/upload/{fkIndentId}")
    public CommonResult busUtensilUpload(@RequestParam("file") MultipartFile file, @PathVariable @Min(value = 1, message = "订单id长度最小1") Long fkIndentId) {
        // 判断上传目录是否存在，不存在则创建
        createUploadDirectory(uploadPath);

        // 判断文件后缀是否为xls或xlsx
        if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
            return CommonResult.fail().setText("文件格式错误！");
        }

        String filePath = uploadPath + file.getOriginalFilename();
        // 进行文件上传操作
        try {
            if (file.isEmpty()) {
                return CommonResult.fail().setText("上传文件为空！");
            }
            Files.copy(file.getInputStream(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail().setText("文件上传失败！");
        }

        try {
            EasyExcel.read(filePath, BusUtensilExcel.class, new BusUtensilListener(fkIndentId)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            String newFilePath = filePath.replace(".xls", ".xlsx");
            renameAndSaveFile(filePath, newFilePath);
            filePath = newFilePath;
            try {
                // 重新执行文件读取
                EasyExcel.read(filePath, BusUtensilExcel.class, new BusUtensilListener(fkIndentId)).sheet().doRead();
            } catch (Exception ex) {
                return CommonResult.fail().setText("文件读取失败！");
            }
        }
        return CommonResult.ok();
    }


    public void renameAndSaveFile(String filePath, String newFileName) {
        logger.info("执行方法 -> renameAndSaveFile, 参数 -> filePath = {} , newFileName = {}", filePath, newFileName);
        try {
            File file = new File(filePath);
            File newFile = new File(newFileName);
            Path sourcePath = file.toPath();
            Path destinationPath = newFile.toPath();
            Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createUploadDirectory(String uploadDirectory) {
        try {
            Files.createDirectories(Paths.get(uploadDirectory));
        } catch (IOException e) {
            e.printStackTrace();
            // 处理目录创建失败的情况
        }
    }
}

